package com.cnswhy.cloud.server.app.controller.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.dto.CustomerReceiverSaveDTO;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.entity.CustomerReceiver;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.customer.CustomerReceiverService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 描述: 客户收件人管理控制层
 * 版权: Copyright (c) 2019
 * 公司: 小鹿科技
 * 作者: 张润泽
 * 版本: 1.0
 * 创建日期: 2019年8月10日
 * 创建时间: 下午4:00:31
 */
@Api(tags = "客户收货地址控制层")
@Controller
@RequestMapping("/customer/receiver")
@Slf4j
public class CustomerReceiverController extends BaseController {


    @Autowired
    private CustomerReceiverService customerReceiveService;

    @Autowired
    private RedisService redisService;

    /**
     * 描述：收件人详情
     * 作者：张润泽
     * 时间：2019年8月6日 下午6:50:20
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "收货地址详情", httpMethod = "POST")
    @ApiParam(name = "id", value = "地址ID")
    @RequestMapping("/detail")
    @ResponseBody
    public RespVo detail(Long id, HttpServletRequest request) {
        RespVo respVo = new RespVo();
        try {
            if (id == null) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("参数异常");
                return respVo;
            }

            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("查询成功");
            respVo.setResult(customerReceiveService.getById(id));
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("查询失败");
            log.error("查询收件人详情异常：", e);
        }
        return respVo;
    }

    /**
     * 描述：保存
     * 作者：张润泽
     * 时间：2019年8月2日 上午10:36:02
     *
     * @param bo
     * @param request
     * @return
     */
    @ApiOperation(value = "保存收货地址", httpMethod = "POST")
    @ApiParam(name = "bo", value = "收货地址对象bO")
    @RequestMapping("/save")
    @ResponseBody
    public RespVo save(CustomerReceiverSaveDTO bo, HttpServletRequest request) {
        RespVo respVo = new RespVo();
        try {
//            CurrentCustomer currentUser = this.getCurrentUser(request);
            Customer loginCustomer = getLoginCustomer( request);
            CustomerReceiver entity = new CustomerReceiver();
            BeanUtils.copyProperties(bo, entity);

            entity.setCustomerId(loginCustomer.getId());
            entity.setIsDefault(bo.getIsDefault());
            customerReceiveService.save(entity);
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("保存成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("保存失败");
            log.error("保存收件人信息异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "查询收货地址列表", httpMethod = "POST")
    @ApiParam(name = "bo", value = "收货地址bO")
    @RequestMapping("/ajaxPage")
    @ResponseBody
    public RespVo ajaxPage(CustomerReceiver bo,
                           @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        RespVo respVo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("查询成功");
            bo.setCustomerId(loginCustomer.getId());
            QueryWrapper<CustomerReceiver> queryWrapper = QueryGenerator.initQueryWrapper(bo);
            queryWrapper.orderByAsc("is_default").orderByDesc("update_time");
            Page<CustomerReceiver> page = new Page<>(currentPage, pageSize);
            IPage<CustomerReceiver> pageList = customerReceiveService.page(page, queryWrapper);
            respVo.setResult(pageList);
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("查询失败");
            log.error("查询收件人信息列表异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "删除收货地址", httpMethod = "POST")
    @ApiParam(name = "id", value = "地址ID")
    @RequestMapping("/delete")
    @ResponseBody
    public RespVo delete(Long id, HttpServletRequest request) {
        RespVo respVo = new RespVo();
        try {
            if (id == null) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("参数异常");
                return respVo;
            }

            CustomerReceiver queryById = customerReceiveService.getById(id);
            if (queryById == null) {
                respVo.setCode(RespVo.CODE_ERROR);
                respVo.setMessage("删除失败，收件人信息不存在");
                return respVo;
            }
            customerReceiveService.removeById(id);
            if (1 == queryById.getIsDefault()) {
                List<CustomerReceiver> customerReceiverList = customerReceiveService.list(Wraps.<CustomerReceiver>lbQ()
                        .eq(CustomerReceiver::getCustomerId, queryById.getCustomerId()).orderByDesc(CustomerReceiver::getUpdateTime));
                for (CustomerReceiver customerReceiver : customerReceiverList) {
                    customerReceiver.setIsDefault(1);
                    customerReceiveService.updateById(customerReceiver);
                    break;
                }
            }
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("删除成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("删除失败");
            log.error("删除收件人信息异常：", e);
        }
        return respVo;
    }

    @ApiOperation(value = "设置默认", httpMethod = "POST")
    @ApiParam(name = "id", value = "地址ID")
    @RequestMapping("/setDefault")
    @ResponseBody
    public RespVo setDefault(Long id, HttpServletRequest request) {
        RespVo respVo = new RespVo();
        try {
            if (id == null) {
                respVo.setCode(RespVo.VALIDATE_ERROR);
                respVo.setMessage("参数异常");
                return respVo;
            }
            Customer loginCustomer = getLoginCustomer( request);
            List<CustomerReceiver> customerReceiverList = customerReceiveService.list(Wraps.<CustomerReceiver>lbQ().eq(CustomerReceiver::getCustomerId, loginCustomer.getId()));
            for (CustomerReceiver customerReceiver : customerReceiverList) {
                if (customerReceiver.getIsDefault() == 1) {
                    customerReceiver.setIsDefault(0);
                    customerReceiveService.updateById(customerReceiver);
                }
            }
            CustomerReceiver customerReceiver = customerReceiveService.getById(id);
            customerReceiver.setIsDefault(1);
            customerReceiveService.updateById(customerReceiver);
            respVo.setCode(RespVo.CODE_SUCCESS);
            respVo.setMessage("设置成功");
        } catch (Exception e) {
            respVo.setCode(RespVo.CODE_ERROR);
            respVo.setMessage("设置失败");
            log.error("设置默认收件人异常：", e);
        }
        return respVo;
    }
}
